package com.liwei.lwmail.cart.controller;

import com.liwei.common.constant.AuthServerConstant;
import com.liwei.lwmail.cart.interceptor.CartInterceptor;
import com.liwei.lwmail.cart.service.CartService;
import com.liwei.lwmail.cart.vo.Cart;
import com.liwei.lwmail.cart.vo.CartItem;
import com.liwei.lwmail.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;


@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @ResponseBody
    @GetMapping("/userCartItems")
    public List<CartItem> getUserCartItems(){
        return cartService.getUserCartItems();
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId")Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.lwmall.com/cart.html";
    }

    @GetMapping("/updateItemNum")
    public String updateItemNum(@RequestParam("skuId")Long skuId, @RequestParam("num")Integer num){
        cartService.updateItemNum(skuId, num);
        return "redirect:http://cart.lwmall.com/cart.html";
    }

    @GetMapping("/updateItemChecked")
    public String updateItemChecked(@RequestParam("skuId")Long skuId, @RequestParam("check")Integer check){
        cartService.updateItemChecked(skuId,check);
        return "redirect:http://cart.lwmall.com/cart.html";
    }

    /**
     * 去购物车页面
     * @return
     */
    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartService.getCart();
        model.addAttribute("cart",cart);
        return "cartList";
    }

    /**
     * 添加购物车
     * @return
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("num") Integer num,
                            RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        cartService.add(skuId,num);
        redirectAttributes.addAttribute("skuId",skuId);
        //防止页面多次刷新
        return "redirect:http://cart.lwmall.com/success.html";
    }

    @GetMapping("/success.html")
    public String successPage(@RequestParam("skuId") Long skuId, Model model){
        CartItem item = cartService.getCartItemBySkuId(skuId);
        model.addAttribute("item",item);
        return "success";
    }
}
